var express = require("express");
var router = express.Router();
const multer = require('multer');
const path = require('path'); 
const fs = require('fs');
const { DynamicContent } = require("../models")
const { BASE_URL } = require('../config');
const { User } = require('../models');

let draftId = null; // 保存【动态】草稿的 id

function createDynamicContent(userPhone) {
    return new Promise((resolve, reject) => {
        DynamicContent
        .create({ phone: userPhone, })
        .then(result => {
            console.log('草稿创建成功');
            resolve(result._id);
        })
        .catch(err => {
            console.error('草稿创建失败', err);
            reject();
        });
    });
}

// 指定【动态】图片的保存路径
const storage = multer.diskStorage({ 
    destination: (req, file, cb) => {
        console.log('req.body.userPhone=', req.body.userPhone);
        
        User
        .findOne({ phone: req.body.userPhone })
        .exec()
        .then(async res => {
            if (res === null) return console.log("没有该用户");

            console.log('res.draft_1', res.draft);
            
            draftId = res.draft;

            // 如果没有【动态】草稿模型，则创建一个
            if (res.draft === null)
            {
                draftId = res.draft = await createDynamicContent(req.body.userPhone);
                res.save();
            }

            // 创建存放【动态】图片的文件夹 
            let newFolderPath = path.join(__dirname, '../public/userFiles/' + req.body.userPhone + '/userDynamic/' + draftId);

            if (!fs.existsSync(newFolderPath)) 
            {	// 判断指定路径下是否有这个文件夹，没有就新建
                fs.mkdirSync(newFolderPath, { recursive: true }, err => console.error('userDynamic文件夹创建失败:', err));
                console.log(newFolderPath + '文件夹创建成功');
            }

            cb(null, newFolderPath);
        })
    },
    filename: (req, file, cb) => {
        const originalName = Buffer.from(file.originalname, 'latin1').toString('utf8');
        cb(null, originalName);
    }
});

const upload = multer({ storage: storage });

// 【动态页面】上传图片存储到服务器之后设置数据库中的图片 url
router.post('/upload', upload.single('file'), (req, res) => {
    // 检测是否上传了文件
    if (!req.file)  return res.status(400).send({ error: '请上传一个文件' });
    
    console.log("draftId_2", draftId);

    // 检测要操作的数据库文档是否为空
    if (draftId === null) 
    {
        console.error('draftId 为空');
        return;
    }

    DynamicContent
    .findOne({ _id: draftId })
    .exec()
    .then(doc => {
        console.log('doc=', doc);
        
        let url = `/userFiles/${ doc.phone }/userDynamic/${ doc._id }/${ Buffer.from(req.file.originalname, 'latin1').toString('utf8') }`

        doc.imageUrls.push(url); // 添加一个元素
        doc.save()
        .then(result => res.status(200).send({ url: BASE_URL + url, filename: req.file.originalname }))
        .catch(err => res.status(500).send({ error: '创建动态内容失败', details: err }));
    })

    draftId = null; // 重置 doc
});

module.exports = router;